package com.qidian.mes.sso.service.impl;

import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.qidian.common.pojo.MESResult;
import com.qidian.common.util.Constant;
import com.qidian.common.util.JWTUtil;
import com.qidian.mes.pojo.User;
import com.qidian.mes.sso.mapper.UserMapper;
import com.qidian.mes.sso.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author 任超
 * Time 2024/10/14 9:51
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JWTUtil jwtUtil;
    @Override
    public MESResult login(String username, String password) {
        // 通过用户名查询用户
        User user = userMapper.selectByUserName(username);
        // 校验登录信息
        if(user == null){// 用户名错误
            return MESResult.error("用户名或密码错误");
        }
        // 校验密码   将传过来的密码进行加密之后再和数据库查询的密码进行比较
        String tempPass = DigestUtils.md5DigestAsHex(password.getBytes());
        if(user.getUserPass().equals(tempPass)){
            // 成功，生成token，
            Map claim = new HashMap();
            claim.put("userId",user.getUserId().toString());// 将userId放入claim
            String token = jwtUtil.getToken(claim);
            // 脱敏处理
            user.setUserPass(null);
            // 返回登录成功的结果
            return MESResult.success(Constant.RESPONSE_STATUS_OK,token,user);
        }
        // 返回登录结果
        return MESResult.error("用户名或密码错误");
    }

    @Override
    public MESResult checkLogin(String token) {
        // 直接校验token
        try {
            jwtUtil.checkToken(token);
        }  catch (TokenExpiredException e) {
            System.err.println("token 已经过期 :" + e.getMessage());
            return MESResult.error("登录已经过期");
        } catch (JWTDecodeException | SignatureVerificationException e){
            return MESResult.error("校验失败");
        }
        // 校验成功
        // 从toke中获取用户编号
        Map<String, Claim> tokenInfo = jwtUtil.getTokenInfo(token);
        Long userId = new Long(tokenInfo.get("userId").asString());
        // 查询用户信息
        User user = userMapper.selectByUserId(userId);
        // 脱敏处理
        user.setUserPass(null);
        return MESResult.success(Constant.RESPONSE_STATUS_OK,token,user);
    }
}
